package edu.se.jai.lesson02.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

@Controller
public class DemoController {

    private static final Logger log = LoggerFactory.getLogger(DemoController.class);

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    // 1. 广播消息 - 所有订阅者都能收到
    @MessageMapping("/broadcast")
    @SendTo("/broadcast")
    public DemoMessage broadcastMessage(DemoMessage message) {
        log.info("收到广播消息: {}", message.getContent());
        message.setTimestamp(System.currentTimeMillis());
        return message;
    }

    // 2. 房间消息 - 根据roomId发送到特定房间
    @MessageMapping("/room/{roomId}/send")
    @SendTo("/room/{roomId}")
    public DemoMessage roomMessage(DemoMessage message, @DestinationVariable String roomId) {
        log.info("房间 {} 收到消息: {}", roomId, message.getContent());
        // 确保roomId正确设置
        message.setRoomId(roomId);
        message.setTimestamp(System.currentTimeMillis());
        return message;
    }

    // 3. 私聊消息 - 发送给指定用户（需要学生自己实现）
    @MessageMapping("/chat/{targetUserId}/send")
    public void chatMessage(DemoMessage message, 
                               @DestinationVariable String targetUserId,
                               @Header("user-id") String senderUserId) {
        log.info("用户 {} 发送私聊给用户 {}: {}", senderUserId, targetUserId, message.getContent());

        // TODO: 需要在这里实现私聊功能
        // 1. 设置消息信息
        // 2. 使用SimpMessagingTemplate发送到目标用户

    }
        


    // 消息实体类
    public static class DemoMessage {
        private String content;
        private String userId;
        private String roomId;
        private long timestamp;

        // Getters and Setters
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
        
        public String getUserId() { return userId; }
        public void setUserId(String userId) { this.userId = userId; }
        
        public String getRoomId() { return roomId; }
        public void setRoomId(String roomId) { this.roomId = roomId; }
        
        public long getTimestamp() { return timestamp; }
        public void setTimestamp(long timestamp) { this.timestamp = timestamp; }
    }
    

}


